package cn.fl.riskctrl.controller;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstValidCardInfoVO;
import cn.fl.riskctrl.service.IRcCstLivLstService;
import fl.constant.facade.framework.constant.DictionaryConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import fl.riskctrl.facade.riskctrl.condition.RcCstLivLstQC;
import cn.fl.riskctrl.vo.RcCstLivLstVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 风险控制活体检测名单表 控制层
 */
@Controller
@RequestMapping("/riskctrl/rccstlivlst")
public class RcCstLivLstController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(RcCstLivLstController.class);

	/**
	 * RcCstLivLst 服务层BEAN
	 */
	@Autowired
	private IRcCstLivLstService rcCstLivLstService;

	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * CstBscInfo 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", " 到列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("riskctrl/rccstlivlst/cstLivMain");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		//系统编码
		String certTypCd = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
		List<KeyValueVO> list = this.sysDictionaryApiService.getKvList(certTypCd, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("certTypCdList", list);
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", " 到列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toModifyPage", " 到修改页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("riskctrl/rccstlivlst/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toModifyPage", " 到修改页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", " 初始化列表.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstNm = request.getParameter("cstNm");
		String certNo = request.getParameter("certNo");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		RcCstLivLstQC qc = new RcCstLivLstQC();
		if (StringUtils.isNotEmpty(cstNm)) {
			//TODO SOMTHING
			qc.setCstNm(cstNm);
		}
		if (StringUtils.isNotEmpty(certNo)) {
			//TODO SOMTHING
			qc.setCertNo(certNo);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.rcCstLivLstService.searchListPage(page);
		List<RcCstLivLstVO> list = (List<RcCstLivLstVO>) pager.getResultList();
		ListPageVO<RcCstLivLstVO> listPage = new ListPageVO<RcCstLivLstVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", " 初始化列表.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "removeById", " 删除数据.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.rcCstLivLstService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "removeById", " 删除数据.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", " 得到一条记录.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			RcCstLivLstVO vo = this.rcCstLivLstService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "getById", " 得到一条记录.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", " 新增.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		RcCstLivLstVO entity = null;
		try {
			entity = this.getRequestParamForRskAdd(request);
			Boolean isCheck = this.checkIdCard(entity.getCertNo());
			if (!isCheck) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("客户身份证格式不正确，请重新输入!");
				return result;
			}
			validCert(entity.getCstNm(), entity.getCertNo(), "客户身份信息验证失败!", "add");
			//TODO ADD PARAM
			Long id = this.rcCstLivLstService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "add", " 新增.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", " 修改.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		RcCstLivLstVO entity = null;
		try {
			entity = this.getRequestParamForRskModify(request);
			Boolean isCheck = this.checkIdCard(entity.getCertNo());
			if (!isCheck) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("客户身份证格式不正确，请重新输入!");
				return result;
			}
			validCert(entity.getCstNm(), entity.getCertNo(), "客户身份信息验证失败!", "modify");
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.rcCstLivLstService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "modify", " 修改.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return result;
	}

	private RcCstLivLstVO getRequestParamForRskAdd(HttpServletRequest request)throws BaseException{
		RcCstLivLstVO rskCtrlMVO = this.getRequestParamForRsk(request);
		rskCtrlMVO.setCrtTm(new Date());
		rskCtrlMVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		return rskCtrlMVO;
	}

	private RcCstLivLstVO getRequestParamForRskModify(HttpServletRequest request)throws BaseException{
		RcCstLivLstVO rcCstLivLstVO = this.getRequestParamForRsk(request);
		rcCstLivLstVO.setMdfTm(new Date());
		rcCstLivLstVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		return rcCstLivLstVO;
	}

	private RcCstLivLstVO getRequestParamForRsk(HttpServletRequest request)throws BaseException{
		String cstNm = request.getParameter("cstNm");//公司名称
		String certTypCd = request.getParameter("certTypCd");//公司编码
		String certNo = request.getParameter("certNo");//请求协议
		String startDt = request.getParameter("startDt");//描述
		String endDt = request.getParameter("endDt");//是否启用
		String isValid = request.getParameter("isValid");//是否启用
		String lstTyp = request.getParameter("lstTyp");//是否启用

		RcCstLivLstVO rcCstLivLstVO = new RcCstLivLstVO();
		rcCstLivLstVO.setCstNm(cstNm.trim());
		rcCstLivLstVO.setCertTypCd(certTypCd.trim());
		rcCstLivLstVO.setCertNo(certNo.trim());
		rcCstLivLstVO.setStartDt(DateUtils.formatStringToDate(startDt,DateUtils.YYYY_MM_DDHHMM));
		rcCstLivLstVO.setEndDt(DateUtils.formatStringToDate(endDt,DateUtils.YYYY_MM_DDHHMM));
		rcCstLivLstVO.setIsValid(Integer.parseInt(isValid.trim()));
		rcCstLivLstVO.setLstTyp(lstTyp.trim());
		return rcCstLivLstVO;
	}

	/**
	 * 证件验证
	 * @param certNm 证件名称
	 * @param certNo 证件号码
	 * @param errorDesc 描述
	 */
	private CstValidCardInfoVO validCert(String certNm, String certNo, String errorDesc, String funName) {
		CstValidCardInfoVO cstValidCardInfoVO = this.cstBscInfoService.validateCstCert(certNm, certNo);
		if(!cstValidCardInfoVO.getSuccess()){
			//第三方验证未通过
			String info = errorDesc+" certNm:" + certNm + " - certNo:" +certNo;
			BaseLogUtils.info(logger, funName, info, CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, errorDesc);
		}
		return cstValidCardInfoVO;
	}

	/**
	 * 验证身份证号码
	 * @param idCard 居民身份证号码15位或18位，最后一位可能是数字或字母
	 * @return 验证成功返回true，验证失败返回false
	 */
	public static boolean checkIdCard(String idCard) {
		String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
		return Pattern.matches(regex,idCard);
	}
}

